package com.mmlc.meimei.lichengkongjian.classify;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.androidnetframe.BaseParentActivity;
import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.responsejavabean.RequestError;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.mmlc.inter.InterFragment;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.YuyueShiyiActivity;
import com.mmlc.meimei.lichengkongjian.dialog.MCenterDialog;
import com.mmlc.network.filter.ShiyijianImreadyRequestFilter;
import com.mmlc.network.filter.ShiyijianRequestFilter;
import com.mmlc.network.filter.ShiyijianShanchuRequestFilter;
import com.mmlc.network.filter.ShiyijiansaomaResultRequestFilter;
import com.mmlc.network.responsebean.ShiyijianResponseBean;
import com.mmlc.utils.SPUtils;
import com.mmlc.utils.TextToSpeek;
import com.mmlc.utils.ToastUtils;
import com.mmlc.utils.XUtils;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 2018/1/11.
 */

public class ShiyijianFragment extends InterFragment {

    TextView  button,button2;
    LinearLayout bottom;
    PullToRefreshListView pullToRefreshListView;
    List<ShiyijianResponseBean.DataBean.ListBean> datas = new ArrayList<>();
    CommonAdapter<ShiyijianResponseBean.DataBean.ListBean> adapter;

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();




    @Override
    protected int initResourceID() {
        return R.layout.activity_shiyijian;
    }

    @Override
    protected void initView() {
        mLocationClient = new LocationClient(getActivity());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        setLocation();
        mLocationClient.start();
        button = (TextView) view.findViewById(R.id.button);
        button2 = (TextView) view.findViewById(R.id.button2);
        bottom = (LinearLayout) view.findViewById(R.id.bottom);
        pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_list);
        pullToRefreshListView.setAdapter(adapter = new CommonAdapter<ShiyijianResponseBean.DataBean.ListBean>(getActivity(), R.layout.content_shiyijian, datas) {
            @Override
            protected void convert(ViewHolder viewHolder, final ShiyijianResponseBean.DataBean.ListBean item, int position) {
                viewHolder.setText(R.id.name, item.getGoods_name());
                viewHolder.setText(R.id.ys, "颜色: " + item.getSpec_color());
                viewHolder.setText(R.id.cm, "尺码: " + item.getSpec_size());
                viewHolder.setText(R.id.count, "1");
                TextView newText=viewHolder.getView(R.id.newText);
                if(item.getIs_new()==1){
                    newText.setVisibility(View.VISIBLE);
                }
                XUtils.image((ImageView) viewHolder.getView(R.id.imageView),item.getImg_thumb());
                viewHolder.setOnLongClickListener(R.id.layout, new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        showNormalDialog(item);
                        return false;
                    }
                });
                viewHolder.setOnClickListener(R.id.layout, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getActivity(), ProductInfoActivity.class);
                        intent.putExtra("name", item.getGoods_name())
                                .putExtra("goods_id", item.getGoods_id());
                        startActivity(intent);
                    }
                });
            }
        });
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                getData();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if(longitude!=0 && latitude!=0) {
            getData();
        }
    }

    double latitude=0;
    double longitude=0;
    public class MyLocationListener extends BDAbstractLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

            latitude = location.getLatitude();    //获取纬度信息
            longitude = location.getLongitude();    //获取经度信息
            getData();
        }
    }

    private void setLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setOpenGps(true);
        option.setLocationNotify(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setWifiCacheTimeOut(5 * 60 * 1000);
        option.setEnableSimulateGps(false);
        mLocationClient.setLocOption(option);
    }
    ShiyijianResponseBean data;
    private void getData() {
        ShiyijianRequestFilter s = new ShiyijianRequestFilter((BaseParentActivity) getActivity());
        if(longitude!=0 && latitude!=0){
            s.requestBean.lat = ""+latitude;
            s.requestBean.lon = ""+longitude;
        }else{
            ToastUtils.showToast("定位失败无法提交获取数据信息");
            return;
        }
        s.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<ShiyijianResponseBean>() {
            @Override
            public void onSuccess(final ShiyijianResponseBean result) {
                pullToRefreshListView.onRefreshComplete();
                if (result.getCode() == 0) {
                    data=result;
                    if(datas.size()!=0){
                        datas.clear();
                    }
                    datas.addAll(result.getData().getList());
                    adapter.notifyDataSetChanged();
                    if (result.getData().getRoom_btn().size()==0) {
                        bottom.setVisibility(View.GONE);
                    } else {
                        bottom.setVisibility(View.VISIBLE);
                    }
                    button.setVisibility(View.GONE);
                    button2.setVisibility(View.GONE);
                    for(int i=0;i<result.getData().getRoom_btn().size();i++){
                        final ShiyijianResponseBean.DataBean.RoomBtnBean roomBtnBean=result.getData().getRoom_btn().get(i);
                        if(i==0){
                            button.setVisibility(View.VISIBLE);
                            button.setText(roomBtnBean.getBtnlabel());
                            button.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (roomBtnBean.getType() == 1) {//预约试衣
                                        yuyue();
                                    } else if (roomBtnBean.getType() == 3) {//imready
                                        imready();
                                    } else if(roomBtnBean.getType() ==2){//店员扫码
                                        saoma(result);
                                    }else if(roomBtnBean.getType()==0){
                                        button.setVisibility(View.GONE);
                                    }
                                }
                            });
                        }else if(i==1){
                            button2.setVisibility(View.VISIBLE);
                            button2.setText(roomBtnBean.getBtnlabel());
                            button2.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (roomBtnBean.getType() == 1) {//预约试衣
                                        yuyue();
                                    } else if (roomBtnBean.getType() == 3) {//imready
                                        imready();
                                    } else if(roomBtnBean.getType() ==2){//店员扫码
                                        saoma(result);
                                    }else if(roomBtnBean.getType()==0){
                                        button2.setVisibility(View.GONE);
                                    }
                                }
                            });
                        }

                    }

                } else {
                    ToastUtils.showToast(getActivity(), result.getMessage());
                }
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);
                pullToRefreshListView.onRefreshComplete();
            }
        });
    }
    MCenterDialog mCenterDialog;
    boolean isCancle=false;
    private void saoma(ShiyijianResponseBean bean){
        if(data!=null){
            View view= LayoutInflater.from(context).inflate(R.layout.dialog_saoma,null);
            ImageView imageView= (ImageView) view.findViewById(R.id.image_saoma);
            XUtils.image(imageView,bean.getData().getRoom_qr());
            view.findViewById(R.id.commit).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mCenterDialog.dissMiss();
                    isCancle=true;
                }
            });
            mCenterDialog=new MCenterDialog(getActivity());
            mCenterDialog.setView(view);
            mCenterDialog.noCancleShow();
            isCancle=false;
            getsaomaResult();
        }

    }

    void getsaomaResult(){
        if(isCancle){
            isCancle=false;
            return;
        }
        ShiyijiansaomaResultRequestFilter shiyijiansaomaResultRequestFilter=new ShiyijiansaomaResultRequestFilter((BaseParentActivity) getActivity());
        shiyijiansaomaResultRequestFilter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<ShiyijianResponseBean>() {
            @Override
            public void onSuccess(final ShiyijianResponseBean result) {
                ToastUtils.showToast(result.getMessage());
                if (result.getCode() == 0) {
                    isCancle=true;
                    mCenterDialog.dissMiss();
                    ToastUtils.showToast(result.getMessage());
                    getData();
                }else{
                    getsaomaResult();
                }

            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                getsaomaResult();
            }
        });
    }

    private void showNormalDialog(final ShiyijianResponseBean.DataBean.ListBean item) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(getActivity());
        normalDialog.setTitle("删除");
        normalDialog.setMessage("您是否要删除该商品?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ShiyijianShanchuRequestFilter s = new ShiyijianShanchuRequestFilter((BaseParentActivity) getActivity());
                        s.requestBean.item_id = item.getId();
                        s.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<ShiyijianResponseBean>() {
                            @Override
                            public void onSuccess(final ShiyijianResponseBean result) {
                                ToastUtils.showToast(result.getMessage());
                                if (result.getCode() == 0) {
                                    datas.remove(item);
                                    adapter.notifyDataSetChanged();
                                }
                            }

                            @Override
                            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                                ToastUtils.showToast(serverError.mess);
                            }
                        });
                    }
                });
        normalDialog.setNegativeButton("关闭", null);
        // 显示
        normalDialog.show();

    }

    public void yuyue() {
        startActivity(new Intent(getActivity(), YuyueShiyiActivity.class));
    }

    public void imready() {
        ShiyijianImreadyRequestFilter s = new ShiyijianImreadyRequestFilter((BaseParentActivity) getActivity());
        s.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<ShiyijianResponseBean>() {
            @Override
            public void onSuccess(final ShiyijianResponseBean result) {
                ToastUtils.showToast(result.getMessage());
                getData();
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);
            }
        });
    }
    TextToSpeek toSpeek;
    public void setNotifyMsg(Context context,String title, String msg){
        String bofangString="";
        int i=0;
        while (i<10){
            i++;
            bofangString+=msg;
        }
        if(mCenterDialog!=null){
            mCenterDialog.dissMiss();
        }
        SPUtils.put(context,"notify_shiyi",true);//已经提示了，点击消息则不在弹出提示消息
        toSpeek = new TextToSpeek(context,bofangString);
        View view= LayoutInflater.from(context).inflate(R.layout.dialog_yuyintishi,null);
        TextView imageView= (TextView) view.findViewById(R.id.content);
        TextView titlet= (TextView) view.findViewById(R.id.title);
        titlet.setText(title);
        imageView.setText(msg);
        view.findViewById(R.id.commit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCenterDialog.dissMiss();
                isCancle=true;
                toSpeek.relese();
            }
        });
        mCenterDialog=new MCenterDialog(context);
        mCenterDialog.setView(view);
        mCenterDialog.noCancleShow();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        toSpeek.relese();
    }
}
